import tkinter as tk
from tkinter import messagebox, simpledialog
import random
import time
import json

class CustomDialog(simpledialog.Dialog):
    def body(self, master):
        tk.Label(master, text="警号:").grid(row=0)
        tk.Label(master, text="姓名:").grid(row=1)

        self.user_id_entry = tk.Entry(master)
        self.name_entry = tk.Entry(master)

        self.user_id_entry.grid(row=0, column=1)
        self.name_entry.grid(row=1, column=1)

        return self.user_id_entry  # initial focus

    def apply(self):
        self.user_id = self.user_id_entry.get()
        self.name = self.name_entry.get()

class QuizApp:
    def __init__(self, root):
        self.root = root
        self.root.title("答题程序")
        self.questions = []
        self.current_question_index = 0
        self.score = 0
        self.timer_running = False
        self.start_time = None
        self.user_id = ""
        self.name = ""
        self.selected_option = None  # 用于单选题和判断题
        self.selected_options = []  # 用于多选题
        self.timeout_dialog = None

        self.load_questions()
        self.create_home_page()

    def load_questions(self):
        # 假设题库文件名为questions.json
        with open('questions.json', 'r', encoding='utf-8') as file:
            self.questions = json.load(file)
        print(f"Loaded {len(self.questions)} questions.")  # 添加调试信息

    def create_home_page(self):
        self.home_frame = tk.Frame(self.root)
        self.home_frame.pack(expand=True)

        start_button = tk.Button(self.home_frame, text="开始答题", command=self.show_login_dialog)
        start_button.pack(pady=20)

    def show_login_dialog(self):
        dialog = CustomDialog(self.root, title="输入信息")
        self.user_id = dialog.user_id
        self.name = dialog.name

        if not self.user_id:
            messagebox.showwarning("警告", "警号不能为空！")
            return

        self.start_quiz()

    def start_quiz(self):
        self.home_frame.pack_forget()
        self.quiz_frame = tk.Frame(self.root)
        self.quiz_frame.pack(expand=True)

        back_button = tk.Button(self.quiz_frame, text="返回首页", command=self.return_to_home)
        back_button.grid(row=0, column=0, sticky=tk.W, padx=10, pady=10)

        self.question_label = tk.Label(self.quiz_frame, text="", wraplength=400)
        self.question_label.grid(row=1, column=0, columnspan=2, pady=10)

        self.next_question()

    def next_question(self):
        if self.current_question_index < len(self.questions):
            question = self.questions[self.current_question_index]
            question_type = question["type"]
            question_text = question["question"]
            options = question["options"]
            correct_answer = question["answer"]
            self.question_label.config(text=f"{self.current_question_index + 1}. {question_text}")

            self.clear_options()

            if question_type == "选择题":
                self.create_choice_buttons(options)
            elif question_type == "判断题":
                self.create_true_false_buttons()
            elif question_type == "多选题":
                self.create_multiple_choice_buttons(options)

            self.correct_answer = correct_answer
            self.current_question_index += 1

            submit_button = tk.Button(self.quiz_frame, text="提交", width=30, height=2, command=self.submit_answer)
            submit_button.grid(row=len(options) + 2, column=0, columnspan=2, pady=10)

            if not self.timer_running:
                self.start_timer()
        else:
            self.end_quiz()

    def clear_options(self):
        for widget in self.quiz_frame.winfo_children():
            if widget.winfo_class() in ["Button", "Checkbutton", "Radiobutton"] and widget.cget("text") != "返回首页":
                widget.destroy()

    def create_choice_buttons(self, options):
        shuffled_options = list(options)
        random.shuffle(shuffled_options)
        self.option_var = tk.StringVar()
        for i, option in enumerate(shuffled_options):
            button = tk.Radiobutton(self.quiz_frame, text=option, variable=self.option_var, value=str(i),
                                    command=lambda i=i: self.select_option(i))
            button.grid(row=i+2, column=0, columnspan=2, pady=5)

    def create_true_false_buttons(self):
        options = ["正确", "错误"]
        self.option_var = tk.StringVar()
        for i, option in enumerate(options):
            button = tk.Radiobutton(self.quiz_frame, text=option, variable=self.option_var, value=str(i),
                                    command=lambda i=i: self.select_option(i))
            button.grid(row=i+2, column=0, columnspan=2, pady=5)

    def create_multiple_choice_buttons(self, options):
        shuffled_options = list(options)
        random.shuffle(shuffled_options)
        self.option_vars = [tk.IntVar() for _ in options]
        for i, option in enumerate(shuffled_options):
            button = tk.Checkbutton(self.quiz_frame, text=option, variable=self.option_vars[i],
                                    command=lambda i=i: self.select_option(i))
            button.grid(row=i+2, column=0, columnspan=2, pady=5)

    def select_option(self, selected_index):
        question = self.questions[self.current_question_index - 1]
        question_type = question["type"]

        if question_type == "选择题" or question_type == "判断题":
            self.selected_option = selected_index
        elif question_type == "多选题":
            if self.option_vars[selected_index].get() == 1:
                if selected_index not in self.selected_options:
                    self.selected_options.append(selected_index)
            else:
                if selected_index in self.selected_options:
                    self.selected_options.remove(selected_index)

    def submit_answer(self):
        question = self.questions[self.current_question_index - 1]
        question_type = question["type"]
        correct_answer = question["answer"]

        if question_type == "选择题":
            if self.selected_option is not None:
                selected_text = self.quiz_frame.winfo_children()[self.selected_option + 2].cget("text")
                if selected_text == correct_answer:
                    self.score += 1
                    messagebox.showinfo("回答正确", "👍")
                else:
                    messagebox.showerror("回答错误", f"正确答案是: {correct_answer}")
            else:
                messagebox.showerror("未选择", "请选择一个选项！")

        elif question_type == "判断题":
            if self.selected_option is not None:
                selected_text = self.quiz_frame.winfo_children()[self.selected_option + 2].cget("text")
                if selected_text == correct_answer:
                    self.score += 1
                    messagebox.showinfo("回答正确", "👍")
                else:
                    messagebox.showerror("回答错误", f"正确答案是: {correct_answer}")
            else:
                messagebox.showerror("未选择", "请选择一个选项！")

        elif question_type == "多选题":
            selected_indices = self.selected_options
            selected_texts = [self.quiz_frame.winfo_children()[i + 2].cget("text") for i in selected_indices]
            if set(selected_texts) == set(correct_answer):
                self.score += 1
                messagebox.showinfo("回答正确", "👍")
            else:
                messagebox.showerror("回答错误", f"正确答案是: {', '.join(correct_answer)}")
            if not selected_indices:
                messagebox.showerror("未选择", "请选择至少一个选项！")

        self.selected_option = None  # 重置单选题和判断题的选择
        self.selected_options = []  # 重置多选题的选择
        self.start_timer()  # 重新启动计时器
        self.after_delay(self.next_question, 2000)

    def end_quiz(self):
        feedback = ""
        if self.score <= 3:
            feedback = "请好好学习！"
        elif self.score == 4:
            feedback = "要继续努力哦！"
        elif self.score == 5:
            feedback = "哇，你超赞的！"
        else:
            feedback = "所有题目已完成！"

        messagebox.showinfo("答题结束", f"你的得分: {self.score}\n{feedback}")
        self.return_to_home()

    def start_timer(self):
        self.timer_running = True
        self.start_time = time.time()
        self.check_timeout()

    def check_timeout(self):
        elapsed_time = time.time() - self.start_time
        if elapsed_time > 60:
            self.timeout_dialog = messagebox.askyesno("提示", "是否继续答题？")
            if self.timeout_dialog:
                self.start_time = time.time()
                self.after_delay(self.check_timeout, 10000)  # 重新启动计时器，等待10秒
            else:
                self.return_to_home()
        else:
            self.after_delay(self.check_timeout, 1000)

    def after_delay(self, func, delay_ms):
        self.root.after(delay_ms, func)

    def return_to_home(self):
        self.current_question_index = 0
        self.score = 0
        self.timer_running = False
        self.selected_option = None
        self.selected_options = []
        self.quiz_frame.pack_forget()
        self.create_home_page()
        if self.timeout_dialog is not None:
            self.timeout_dialog = None

if __name__ == "__main__":
    root = tk.Tk()
    app = QuizApp(root)
    root.mainloop()
